package com.hc.kotlin_coroutine

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.runBlocking

fun main() {
    runBlocking {
        println("------flatMapConcat------")
        flowOf(2000,1000,3000).flatMapConcat {
            flow {
                delay(it.toLong())
                emit(it)
            }
        }.flatMapConcat {
            flowOf("a$it","b$it")
        }.collect{
            println(it)
        }
        //模拟根据token获取用户信息
        getToken().flatMapConcat {
            getUserInfo(it)
        }.flowOn(Dispatchers.IO).collect{
            println(it)
        }
        println("------flatMapMerge------")
        flowOf(2000,1000,3000).flatMapMerge {
            flow {
                delay(it.toLong())
                emit("a$it")
                emit("b$it")
            }
        }.collect{
            println(it)
        }
        println("------flatMapLatest------")
        flow {
            emit(1)
            delay(1000)
            emit(2)
            delay(500)
            emit(3)
        }.flatMapLatest {
            flow {
                delay(800)
                emit(it)
            }
        }.collect{
            println(it)
        }
    }
}

fun getToken():Flow<String> = flow {
    val token = "123456"
    emit(token)
}
fun getUserInfo(token:String):Flow<String> = flow {
    var userinfo:String
    if(token=="123456"){
        userinfo = "张三"
    }else{
        userinfo = "未知"
    }
    emit(userinfo)
}